﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NBlock.MVCExtensions;
using NBlock.Components.Excel;
using Cost.Services;
using Cost.Models;
using System.Data.SqlClient;
using NBlock.Core;
using NBlock.Core.ORM;
using System.Linq.Expressions;

namespace Cost.Controllers
{
    public class DishOrderController : Controller
    {
        private readonly ICostRepository<DishOrder> dishorderRepository;
        private readonly ICostRepository<DishOrderItemView> dishorderitemRepository;
        private readonly ICostRepository<ProjectSite> projectSiteRepository;

        private readonly OrderService orderService;

        public DishOrderController(ICostRepository<DishOrder> dishorderRepository,
            ICostRepository<DishOrderItemView> dishorderitemRepository,
            ICostRepository<ProjectSite> projectSiteRepository,
            OrderService orderService)
        {
            this.dishorderRepository = dishorderRepository;
            this.dishorderitemRepository = dishorderitemRepository;
            this.orderService = orderService;
            this.projectSiteRepository = projectSiteRepository;
        }

        //
        // GET: /DishOrder/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult List(nbPageInfo pager, nbSearchCondition where)
        {
            var siteId = nbUserContext.Current.CurrentUser.UnitCode;
            var pageData = dishorderRepository.GetPageable(pager, d => d.SiteId == siteId, where);
            var data = pager.ToGridData(pageData);
            return Json(data);
        }

        public ActionResult Edit(string Id)
        {
            var data = dishorderRepository.Find(Id) ?? new DishOrder();
            if (string.IsNullOrEmpty(data.CreateUserId))
            {
                data.ReportDate = DateTime.Now;
            }
            data.SiteId = nbUserContext.Current.CurrentUser.UnitCode;
            return View(data);
        }

        [HttpPost]
        public JsonResult EditList(string OrderId, nbPageInfo pager, nbSearchCondition where)
        {
            var list = dishorderitemRepository.GetPageable(pager, m => m.OrderId == OrderId, where);
            var pageList = list.Page.ToList();
            var fdata = pager.ToGridData(pageList, list.Total);
            return Json(fdata);
        }

        #region 正式订单
        public ActionResult Offer()
        {
            return View();
        }

        [HttpPost]
        public JsonResult OfferList(nbPageInfo pager, nbSearchCondition where)
        {
            var siteId = nbUserContext.Current.CurrentUser.UnitCode;
            var pageData = dishorderRepository.GetPageable(pager, d => d.SiteId == siteId && d.OrderType == "正式订单", where);
            var data = pager.ToGridData(pageData);
            return Json(data);
        }

        public ActionResult OfferEdit(string Id)
        {
            var data = dishorderRepository.Find(Id) ?? new DishOrder
            {
                OrderDate = DateTime.Today.AddDays(2),
                OrderType = "正式订单",
                State = "草稿",
                SiteId = nbUserContext.Current.CurrentUser.UnitCode,
                SiteName = nbUserContext.Current.CurrentUser.UnitName,
            };

            // 子表数据
            ViewBag.DishList = GetOfferItems(data.Id);

            return View(data);
        }

        private IList<DishOrderItemView> GetOfferItems(string orderId)
        {
            var list = dishorderitemRepository.FindAll(p => p.OrderId == orderId).ToList();
            return list;
        }

        [HttpPost]
        public JsonResult SaveOffer(string Id, DateTime orderDate, IList<DishOrderItem> dishList)
        {
            if (orderDate < DateTime.Today.AddDays(2))
            {
                var err = new nbAjaxMessage
                {
                    IsSuccess = false,
                    Msg = string.Format("订单必须提前两天上报！")
                };
                return Json(err);
            }

            if (dishList == null || dishList.Count < 1)
            {
                var err = new nbAjaxMessage
                {
                    IsSuccess = false,
                    Msg = string.Format("请先添加菜肴信息！")
                };
                return Json(err);
            }

            var order = dishorderRepository.Find(Id) ?? new DishOrder();

            // 清空所有的子表信息
            orderService.DeleteDishOrderItem(order.Id);

            // 保存订单信息
            TryUpdateModel(order);
            orderService.SaveDishOrder(order, dishList);

            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult OfferDelete(string Id)
        {
            orderService.DeleteDishOrder(Id);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult OfferDeleteAll(string Ids)
        {
            orderService.DeleteDishOrder(Ids);
            return Json(nbAjaxMessage.Successful);
        }

        public ActionResult OfferReportOrder(string Id)
        {
            var data = dishorderRepository.Find(Id);

            if (!data.ReportDate.HasValue)
            {
                data.ReportDate = DateTime.Now;
            }
            if (string.IsNullOrWhiteSpace(data.ReportUserName))
            {
                data.ReportUserId = nbUserContext.Current.CurrentUser.UserId;
                data.ReportUserName = nbUserContext.Current.CurrentUser.UserName;
            }

            return View(data);
        }

        [HttpPost]
        public JsonResult SaveOfferReportOrder(string Id, string password)
        {
            var data = dishorderRepository.Find(Id);

            // 判断上报密码是否正确
            //var pwd = projectSiteRepository.FindAll(s => s.Id == data.SiteId).Select(s => s.ReportOrderPassword).FirstOrDefault();
            //if (password == pwd)
            //{
            // 更改订单的状态和统计订单的数量
            TryUpdateModel(data);
            orderService.ReportOrder(data);
            return Json(nbAjaxMessage.Successful);
            //}
            //else
            //{
            //    return Json(new nbAjaxMessage { IsSuccess = false, Msg = "上报密码错误，请重新输入的正确密码！" });
            //}

        }
        #endregion

        #region 订单上报情况
        public ActionResult ReportOrder()
        {
            return View();
        }

        [HttpPost]
        public JsonResult ReportList(DateTime? OrderDate, nbPageInfo pager, nbSearchCondition where)
        {
            Expression<Func<DishOrder, bool>> filter = o => o.State == "上报";
            if (OrderDate.HasValue)
            {
                filter = filter.And(o => o.OrderDate == OrderDate);
            }

            var pageData = dishorderRepository.GetPageable(pager, filter, where);
            var data = pager.ToGridData(pageData);
            return Json(data);
        }

        public ActionResult ReportOrderView(string Id)
        {
            var data = dishorderRepository.Find(Id);
            ViewBag.detail = dishorderitemRepository.FindAll(m => m.OrderId == Id);
            return View(data);
        }

        #endregion

        #region 同步指定日期的订单品名价格
        public ActionResult SyncMaterialPrice(DateTime? date)
        {
            var result = "成功";
            if (date.HasValue)
            {
                orderService.SyncMaterialPrice(date.Value);
            }
            else
            {
                result = "日期输入不对";
            }
            return Content(result);
        }
        #endregion
    }

    public class DishOrderEx
    {
        public string DishId { get; set; }
        public string Name { get; set; }
        public Nullable<decimal> TotalCost { get; set; }
        public Nullable<DateTime> Date { get; set; }
    }
}
